/**
 * Copyright 2018-2020 stylefeng & fengshuonan (https://gitee.com/stylefeng)
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mainbo.core.shiro.service.impl;

import cn.hutool.core.convert.Convert;
import com.mainbo.core.common.constant.factory.ConstantFactory;
import com.mainbo.core.common.constant.state.ManagerStatus;
import com.mainbo.core.shiro.SessionKey;
import com.mainbo.core.shiro.ShiroKit;
import com.mainbo.core.shiro.ShiroUser;
import com.mainbo.core.shiro.service.UserAuthService;
import com.mainbo.core.util.WebThreadLocalUtils;
import com.mainbo.modular.system.dao.*;
import com.mainbo.modular.system.model.*;
import cn.stylefeng.roses.core.util.SpringContextHolder;
import org.apache.shiro.authc.CredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
@DependsOn("springContextHolder")
@Transactional(readOnly = true)
public class UserAuthServiceServiceImpl implements UserAuthService {

    @Resource
    private PtAccountMapper accountMapper;

    @Resource
    private MenuMapper menuMapper;
    @Resource
    private PtEduEmpMapper ptEduEmpMapper;
    @Resource
    private PtStudentMapper ptStudentMapper;
    @Resource
    private PtTeacherMapper ptTeacherMapper;
    @Resource
    private PtPeopleMapper ptPeopleMapper;
    @Resource
    private PtRoleTypeMapper roleTypeMapper;


    public static UserAuthService me() {
        return SpringContextHolder.getBean(UserAuthService.class);
    }

    @Override
    public PtAccount user(String account) {

        PtAccount user = accountMapper.getByAccount(account);

        // 账号不存在
        if (null == user) {
            throw new CredentialsException();
        }
        // 账号被冻结
        if (!user.getEnable()) {
            throw new LockedAccountException();
        }
        if (user != null && user.getUserInfo() == null) {
            CommUser userInfo = null;
            switch (Objects.requireNonNull(SysRole.getRoleById(user.getUserType()))) {
                case AREAWORKER:
                case AREAMANAGER:
                    userInfo = ptEduEmpMapper.getById(user.getId());
                    break;
                case STUDENT:
                    userInfo = ptStudentMapper.getById(user.getId());
                    break;
                case TEACHER:
                case SCHWORKER:
                case SCHMANAGER:
                    userInfo = ptTeacherMapper.getById(user.getId());
                    break;
                default:
                    userInfo = ptPeopleMapper.getById(user.getId());
                    break;
            }
            user.setUserInfo(userInfo);

        }
        if (ShiroKit.getSessionAttr(SessionKey.CURRENT_USER) == null) {
            ShiroKit.setSessionAttr(SessionKey.CURRENT_USER, user);
        }

        return user;
    }

    @Override
    public ShiroUser shiroUser(PtAccount user) {
        ShiroUser shiroUser = new ShiroUser();

        shiroUser.setId(user.getId());
        shiroUser.setAccount(user.getAccount());
        shiroUser.setOrgId(user.getOrgId());
        shiroUser.setOrgName(ConstantFactory.me().getOrgName(user.getOrgId()));
        shiroUser.setName(user.getUserInfo().getName());

        //Integer[] roleArray = Convert.toIntArray(user.getRoleid());
       // List<Integer> roles = userRoleMapper.findUserRoles(user.getId());
        PtRoleType roleType= roleTypeMapper.selectById(user.getUserType());
        List<Integer> roleList = new ArrayList<Integer>();
        List<String> roleNameList = new ArrayList<String>();
//        for (int roleId : roles) {
//            roleList.add(roleType.getId());
//            roleNameList.add(ConstantFactory.me().getSingleRoleName(roleId));
//        }
        roleList.add(roleType.getId());
        roleNameList.add(roleType.getRoleTypeName());
        shiroUser.setRoleList(roleList);
        shiroUser.setRoleNames(roleNameList);

        return shiroUser;
    }

    @Override
    public List<String> findPermissionsByRoleId(Integer roleId) {
        return menuMapper.getResUrlsByRoleId(roleId);
    }

    @Override
    public String findRoleNameByRoleId(Integer roleId) {
        return ConstantFactory.me().getSingleRoleName(roleId);
    }

//    @Override
//    public SimpleAuthenticationInfo info(ShiroUser shiroUser, PtAccount user, String realmName) {
//        String credentials = "123456";
//
////        // 密码加盐处理
////        String source = user.getSalt();
////        ByteSource credentialsSalt = new Md5Hash(source);
//        return new SimpleAuthenticationInfo(shiroUser.getId(), credentials.toString(), realmName);
//
//    }

}
